﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DafYomiLib
{
    public static class Gimatriya
    {
        private readonly static Dictionary<uint, char> s_gimatriyaValues = new Dictionary<uint, char>
            {
                { 400, 'ת' },
                { 300, 'ש' },
                { 200, 'ר' },
                { 100, 'ק' },
                { 90, 'צ' },
                { 80, 'פ' },
                { 70, 'ע' },
                { 60, 'ס' },
                { 50, 'נ' },
                { 40, 'מ' },
                { 30, 'ל' },
                { 20, 'כ' },
                { 10, 'י' },
                { 9, 'ט' },
                { 8, 'ח' },
                { 7, 'ז' },
                { 6, 'ו' },
                { 5, 'ה' },
                { 4, 'ד' },
                { 3, 'ג' },
                { 2, 'ב' },
                { 1, 'א' },
            };

        public static string Convert(int number)
        {
            var gimatriyaString = new StringBuilder();

            foreach (var gimatriyaValue in s_gimatriyaValues.Keys.OrderByDescending(a => a))
            {
                if (number == 0)
                {
                    break;
                }

                if (number == 15 || number == 16)
                {
                    gimatriyaString.Append("ט");
                    gimatriyaString.Append(number == 15 ? 'ו' : 'ז');
                    break;
                }

                var div = (int)(number/gimatriyaValue);
                if (div == 0)
                {
                    continue;
                }

                gimatriyaString.Append(new string(s_gimatriyaValues[gimatriyaValue], div));
                number -= div*(int)gimatriyaValue;
            }

            return gimatriyaString.ToString();
        }
    }
}
